package com.briup.mt.web.controller;


import com.briup.mt.bean.Application;
import com.briup.mt.service.IApplicationService;
import com.briup.mt.utils.ExcelUtils;
import com.briup.mt.utils.Message;
import com.briup.mt.utils.MessageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Validated
@RequestMapping("/Application")
public class ApplicationController {

    @Resource
    private IApplicationService applicationService;


    @GetMapping("query")
    public Message query(String name,String telephone,String type){
        List<Application> list = applicationService.query(name, telephone,type);
        return MessageUtil.success(list);
    }

    @PostMapping("saveOrUpdate")
    public Message saveOrUpdate(Application application){
        applicationService.saveOrUpdate(application);
        return MessageUtil.success(application);
    }

    @DeleteMapping("deleteById")
    public Message deleteById(long id){
        applicationService.deleteById(id);
        return MessageUtil.success("操作成功");
    }

    @ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
    @GetMapping("download")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
             })
    public void download(HttpServletResponse response,String name,String telephone,String type) throws Exception {
        List<Application> list = applicationService.query(name, telephone,type);
        // 2. 将excel导出
        // 2.1 excel头部数据
        String[] headList = new String[] { "名称", "类型", "简介", "email", "联系电话", "经度", "纬度" };
        // 2.2 属性
        String[] fieldList = new String[] { "name", "type", "introduce", "email", "telephone", "longitude", "latitude" };
        // 2.3 数据列，需要转化
        List<Map<String, Object>> dataList = new ArrayList<>();

        for (Application app : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", app.getName());
            map.put("type", app.getType());
            map.put("introduce", app.getIntroduce());
            map.put("telephone", app.getTelephone());
            map.put("longitude", app.getLongitude());
            map.put("latitude", app.getLatitude());
            dataList.add(map);
        }
        // 2.4 导出文件名
        String excelName = "applications";
        // 3. 调用工具方法导出Excel
        ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

    }

}
